import { _decorator, Component, Node, resources, SpriteFrame, Sprite, UITransform, Layers } from 'cc'
import DataManager from '../../Runtime/DataManager'
import ResourceManager from '../../Runtime/ResourceManager'
import { createUINode, randomByRange } from '../../Utils'
import { TileManager } from './TileManager'
const { ccclass } = _decorator

/**
 * Predefined variables
 * Name = TileMapManager
 * DateTime = Tue Jul 05 2022 16:53:17 GMT+0800 (中国标准时间)
 * Author = Zero_Y
 * FileBasename = TileMapManager.ts
 * FileBasenameNoExtension = TileMapManager
 * URL = db://assets/Scripts/Tile/TileMapManager.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */

@ccclass('TileMapManager')
export class TileMapManager extends Component {
  async init() {
    // 从数据中心取出
    const { mapInfo } = DataManager.Instance
    // 加载资源
    const spriteFrames = await ResourceManager.Instance.loadDir('texture/tile/tile')
    DataManager.Instance.tileInfo = []
    for (let i = 0; i < mapInfo.length; i++) {
      DataManager.Instance.tileInfo[i] = []
      for (let j = 0; j < mapInfo[i].length; j++) {
        const item = mapInfo[i][j]
        if (item.src === null || item.type === null) {
          continue
        }
        const node = createUINode()
        let srcNumber = item.src
        // 指定渲染随机瓦片,并且加条件,偶数的瓦片才随机
        if ((srcNumber === 1 || srcNumber === 5 || srcNumber === 9) && i % 2 === 0 && j % 2 === 0) {
          srcNumber += randomByRange(0, 4)
        }
        const spriteFrame = spriteFrames.find(v => v.name === `tile (${srcNumber})`) || spriteFrames[0]
        const tileManager = node.addComponent(TileManager)
        const type = item.type
        tileManager.init(type, spriteFrame, i, j)
        DataManager.Instance.tileInfo[i][j] = tileManager
        node.setParent(this.node)
      }
    }
  }
}
